<template>
  <div>
    <el-row class="back-head" type="flex" align="middle">
      <span @click="backPath()" style="cursor: pointer;line-height: 32px"><i class="el-icon-arrow-left"></i>返回</span>
      <span>编辑配送费参数</span>
    </el-row>
    <el-row class="main">
      <el-form :model="params" ref="ruleForm" label-width="120px" label-position="right" size="small">
        <el-row class="head" type="flex" align="middle">基本参数</el-row>
        <div class="item">
          <el-form-item label="时间设置" required style="margin-bottom: 0">
            <el-row type="flex" v-for="(item,index) in params.timesolts" :key="index">
              <el-row type="flex">
                <el-form-item :prop="'timesolts.' + index + '.starttime'" :rules="[{ required: true, message: '请选择时间段'}]"
                  style="width: 100px; margin-bottom:18px">
                  <el-time-select style="width: 100%" placeholder="起始" v-model="item.starttime" :editable="false" :clearable="false"
                    :picker-options="{start: '00:00',step: '00:30',end: '24:00'}"/> 
                </el-form-item>
                <span style="margin: 0 5px;line-height: 32px;">至</span>
                <el-form-item :prop="'timesolts.' + index + '.endtime'" :rules="[{ required: true, message: '请选择时间段'}]"
                  style="width: 100px; margin-bottom:18px">
                  <el-time-select style="width: 100%" placeholder="结束" v-model="item.endtime" :editable="false" :clearable="false"
                    :picker-options="{start: '00:00',step: '00:30',end: '24:00',minTime: item.starttime}" />
                </el-form-item>
                <span style="line-height: 32px;margin: 0 5px;">时间内</span>
                <el-form-item :prop="'timesolts.' + index + '.timeCost'" :rules="[{ required: true, message: '请输入金额'}]">
                  <el-input-number v-model="item.timeCost" :min='0' :max='9999' :precision='2'/> 
                </el-form-item>
                <span style="line-height: 32px;margin: 0 5px;">{{comConfig.unit}}配送费，超出每{{comConfig.lengthUnit}}</span>
                <el-form-item :prop="'timesolts.' + index + '.charge'" :rules="[{ required: true, message: '请输入金额'}]">
                  <el-input-number v-model="item.charge" :min='0' :max='9999' :precision='2'/>
                </el-form-item>
                <span style="line-height: 32px;margin:0 15px 0 5px;">{{comConfig.unit}}配送费</span>
              </el-row>
              <div v-if='index== 0 && params.timesolts.length< 5' class="butns" >
                <el-button type='primary' style='padding: 6px 4px' size='mini' :disabled='!isshow' icon='el-icon-circle-plus-outline' @click="addDistanceCharge()">
                  ({{params.timesolts.length}}/5)
                </el-button>
              </div>
              <div v-if="index >0" class="flex-row-ver butnsdel" @click="delDistanceCharge()"><i class="el-icon-remove"></i></div>
            </el-row>
          </el-form-item>
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="基础配送距离" prop="nocharge" :rules="[{ required: true, message: '请输入距离'}]">
                <el-input-number style="margin-right: 5px" v-model="params.nocharge" :min='0' :max='9999' :precision='1'/> {{comConfig.lengthUnit}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大配送距离" prop="maxdistance" :rules="[{ required: true, message: '请输入距离'}]">
                <el-input-number style="margin-right: 5px" v-model="params.maxdistance" :min='0' :max='9999' :precision='1'/> {{comConfig.lengthUnit}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="12">
              <el-form-item label="配送速度" prop="speed" :rules="[{ required: true, message: '请输入数值'}]">
                <el-input-number style="margin-right: 5px" v-model="params.speed" :min='0' :max='9999' :precision='1' /> 分/100 {{comConfig.mLengthUnit}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高配送费" prop="maxcharge" :rules="[{ required: true, message: '请输入金额'}]">
                <el-input-number style="margin-right: 5px" v-model="params.maxcharge" :min='0' :max='9999' :precision='2'/> {{comConfig.unit}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="自动完成订单" prop="updatehour" :rules="[{ required: true, message: '请输入数值'}]">
            <el-input-number style="margin-right: 5px" v-model="params.updatehour" :min='0' :max='24' :precision='0'/> 小时后(针对商家自配送)
          </el-form-item>
        </div>
        <el-row class="head" type="flex" align="middle">其他附加费<span style="color: #999;font-size: 12px;">(选填)</span></el-row>
        <div class="item">
          <el-form-item label="附加费名称" prop="name" :rules="[{ required: params.appends.length > 0, message: '请输入附加费名称'}]">
            <el-input style="width: 460px;" v-model="params.name" />
          </el-form-item>
          <el-form-item label="附加费选项" style="margin-bottom: 0">
            <el-row type="flex">
              <el-row>
                <el-row type="flex" v-for="(item,index) in params.appends" :key="index">
                  <el-form-item style="width: 400px;margin-right: 10px;" :prop="'appends.' + index + '.content'"
                    :rules="[{ required: true, message: '请输入附加费选项名称'}]">
                    <el-input type='text' v-model="item.content" placeholder="如：1层、2到5层、6层以上等..." clearable />
                  </el-form-item>
                  <el-form-item :prop="'appends.' + index + '.cost'" :rules="[{required: true, message: '金额未填写'}]">
                    <el-input-number placeholder="请输入金额" :min='0' :max="99999" :precision='2' v-model="item.cost" />
                  </el-form-item>
                  <span style='margin: 0 5px;'>{{comConfig.unit}}</span>
                  <div v-if="index=== (params.appends.length-1)" class="flex-row-ver butnsdel" @click="delWeightSurcharge()">
                    <i class="el-icon-remove"></i>
                  </div>
                </el-row>
              </el-row>
              <div v-if='params.appends.length< 10' class="butns">
                <el-button type='primary' style='padding: 6px 4px' size='mini' icon='el-icon-circle-plus-outline' @click="addWeightSurcharge()">
                  ({{params.appends.length}}/10)
                </el-button>
              </div>
            </el-row>
          </el-form-item>
        </div>
        <el-row class="head" type="flex" align="middle" v-if="!isChina">商品外汇价格设置</el-row>
        <div class="item" v-if="!isChina">
          <el-form-item label="对人民币汇率" prop="exchangeRate" :rules="[{ required: !this.isChina, message: '请输入对人民币的汇率'}]">
            <el-input-number :min='0' :max="99999" :precision='4' v-model="params.exchangeRate" />
          </el-form-item>
        </div>
        <el-row class="head" type="flex" align="middle">配送区域</el-row>
        <div class="item">
          <el-form-item label-width="0" prop="distrange" :rules="[{ required: true, message: '配送区域未选',trigger:'change' }]">
            <gaode-map v-if="isChina" :deliveryArea ="deliveryArea" :agentArea = "agentArea" :search="searchName" @surDistrange="surDistrange" class="base-diy-map" />
            <google-map v-else :deliveryArea ="deliveryArea" :agentArea = "agentArea" :search="searchName" @surDistrange="surDistrange" class="base-diy-map" />
          </el-form-item>
        </div>
        <el-row>
          <el-form-item>
            <el-button type="primary" :loading="loadingSubmit" @click="submitForm('ruleForm')">保存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-row>
  </div>
</template>
<script>
  import gaodeMap from './components/gaodeMap'
  import googleMap from './components/googleMap'
  import { kmToOtherUnit, otherUnitToKm, mToOtherUnit, otherUnitToM } from '@/utils/unitChange.js'
  export default {
    components: { gaodeMap, googleMap },
    data() {
      return {
        loadingSubmit: false,
        params: {
          nocharge: undefined,
          speed: undefined,
          maxcharge: undefined,
          maxdistance: undefined,
          updatehour: undefined,
          distrange: '',
          firstTime: '',
          timesolts:[ //开始时间结束时间的数组
            {starttime: '', endtime:'', timeCost: undefined, charge: undefined }
          ],
          appends: [], // 骑手爬楼费用
          name: '',
          exchangeRate: undefined
        },
        deliveryArea: '', // 配送区域
        agentArea: '', // 代理商区域
        isshow: false,
        searchName: '' // 模糊检索
      }
    },
    watch: {
      'params.timesolts': {
        handler(newValue) {
          this.isshow = this.isShowEbutton(newValue)
        },
        deep: true
      }
    },
    methods: {
      isShowEbutton(arr){
        let isShow = true
        arr.forEach((item)=>{
          if(item.starttime === '' || item.endtime === '' || item.timeCost === '' || item.charge === ''){
            isShow = false
            return isShow
          }
        })
        return isShow
      },
      addDistanceCharge() {
        this.params.timesolts.push({starttime: '', endtime:'', timeCost: undefined, charge: undefined })
      },
      delDistanceCharge() {
        this.params.timesolts.pop()
      },
      addWeightSurcharge() { // 添加爬楼费用
        this.params.appends.push({ content: '', cost: undefined })
      },
      delWeightSurcharge() { // 删除爬楼费用
        this.params.appends.pop()
      },
      surDistrange(e) { // 确认所选配送区域
        this.params.distrange = e
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const params = { ...this.params }
            params.agentid = this.$route.query.aid
            params.nocharge = otherUnitToKm(params.nocharge)
            params.maxdistance = otherUnitToKm(params.maxdistance)
            params.speed = otherUnitToM(params.speed)
            params.timesolts = params.timesolts.map((item)=>{
              const obj = {
                starttime: item.starttime ? `1970-01-01 ${item.starttime}:00` : '',
                endtime: item.endtime ? (item.endtime === '24:00' ? '1970-01-01 23:59:59':`1970-01-01 ${item.endtime}:00`) : '',
                charge: item.charge ? kmToOtherUnit(item.charge) : '',
                timeCost:item.timeCost
              }
              return obj
            })
            this.loadingSubmit = true
            if (this.$route.query.id) {
              params.id = this.$route.query.id
              this.$http.post('/server/deliverCost/update', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '修改成功！'})
                  this.$router.push('/main/agent/delivery')
                }
              }).finally(() => { this.loadingSubmit = false })
            } else {
              this.$http.post('/server/deliverCost/save', JSON.stringify(params)).then(res => {
                if (res.data.success) {
                  this.$message({type: 'success', message: '新增成功！'})
                  this.$router.push('/main/agent/delivery')
                }
              }).finally(() => { this.loadingSubmit = false })
            }
          }
        })
      },
      getDateInfo() {  //获取数据
        const params = {id: this.$route.query.id, agentid: this.$route.query.aid}
        this.$http.get('/server/deliverCost/info?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            const r = res.data.data
            this.params.nocharge = r.nocharge ? kmToOtherUnit(r.nocharge) : ''
            this.params.speed = r.speed ? mToOtherUnit(r.speed) :  ''
            this.params.maxcharge = r.maxcharge ? r.maxcharge :  ''
            this.params.maxdistance = r.maxdistance ? kmToOtherUnit(r.maxdistance) :  ''
            this.params.updatehour = r.updatehour ? r.updatehour :  ''
            this.params.name = r.name || ''
            this.params.exchangeRate = r.exchangeRate ||  ''
            this.params.appends = r.appends || []
            this.params.timesolts = r.timesolts && r.timesolts.length ? r.timesolts.map((item) => {
              const obj = {
                starttime: item.starttime || '',
                endtime: item.endtime ? (item.endtime =='23:59'? '24:00':item.endtime): '',
                timeCost: item.timeCost >= '0' ? item.timeCost :  '',
                charge: item.charge >= '0' ? otherUnitToKm(item.charge) :  ''
              }
               return obj
            }) : [{starttime: '', endtime:'', timeCost: undefined, charge: undefined }]
              this.params.distrange = r.distrange ? r.distrange : ''
            if (r.distrange) this.deliveryArea = r.distrange
          }
        })
      },
      getAgentInfo(id) { // 定位代理商
        this.$http.get('/server/agent/info?' + this.qs.stringify({id})).then(res => {
          if (res.data.success) {
            const a = res.data.data
            this.searchName = (a.province || '') + (a.cityname || '') + (a.countyname || '')
            if (a.distrange) this.agentArea = a.distrange
            if (this.$route.query.id) this.getDateInfo()
          }
        })
      },
      backPath() {
        this.$router.replace({path: '/main/agent/delivery'})
      }
    },
    mounted() {
      if (this.$route.query.aid) {
        this.getAgentInfo(this.$route.query.aid)
      } else {
        this.$message({type: 'error', message: '当前页面信息有误!'})
        this.$router.push({path: '/main/agent/delivery'})
      }
    }
  }
</script>
<style scoped>
  .back-head {
    height: 50px;
    padding: 0 15px;
    border-bottom: 1px solid #e2e2e2;
  }
  .back-head span {
    margin-left: 20px;
    font-size: 16px;
    font-weight: bold;
  }
  .main {
    min-width: 910px;
    max-width: 1400px;
    padding: 20px 15px 100px 15px;
    margin: 0 auto;
  }
  .main .head {
    height: 40px;
    padding: 0 15px;
    background: #eff0f5;
    font-weight: bold;
    font-size: 15px;
  }
  .main .item {
    padding: 15px;
    margin-bottom: 30px;
    border-radius: 0 0 4px 4px;
    border: 1px solid #e5e5e5;
    border-top: none;
  }
  .base-diy-map {
    width: 100%;
    height: 600px;
  }
  .item .butnsdel {
    cursor: pointer;
    text-align: center;
    margin-left: 20px;
    padding: 0 5px;
    height: 32px;
    line-height: 32px
  }
  .item .butnsdel i {
    font-size: 25px;
    color: #f56c6c;
  }
</style>
